import Message from '@/components/XtxMessage'
import useStore from '@/store'
import Home from '@/views/Home/Home.vue'
import LayoutVue from '@/views/Layout/Layout.vue'
import { createRouter, createWebHashHistory } from 'vue-router'
const router = createRouter({
  history: createWebHashHistory(),
  scrollBehavior: () => {
    return {
      top: 100
    }
  },
  routes: [
    {
      path: '/',
      component: LayoutVue,
      children: [
        {
          path: '',
          component: Home
        },
        {
          path: 'Category/:id',
          component: () => import('@/views/Category/Category.vue')
        },
        {
          path: 'goods/:id',
          component: () => import('@/views/Goods/Goods.vue')
        },
        {
          path: 'cart',
          component: () => import('@/views/Cart/Cart.vue')
        },
        {
          path: 'member/checkout',
          component: () => import('@/views/member/pay/checkout.vue')
        }
      ]
    },
    {
      path: '/login',
      component: () => import('@/views/Login/Login.vue'),
    },
    {
      path: '/login/callback',
      component: () => import('@/views/Login/Callback.vue'),
    },

  ]

})

// router.beforeEach((to,from,next)=>{
//   // 判断用户有没有登陆
//   const {cart} = useStore()
//   if(cart.isLogin){
//     next()
//   }else{
//     next('/login')
//   }

// })

// 配置路由导航守卫，拦截 /member开头的所有的地址
/* router.beforeEach((to, from, next) => {
  // 判断用户登没登录
  const { cart } = useStore()
  if (cart.isLogin) {
    next()
  } else {
    Message.error('没有登陆不能进')
    if (to.path.includes('/member')) {
      next({
        path: '/login',
       query: {
         redirectUrl: to.fullPath
       }    })
    } else {
      next()
    }
  }
}) */
router.beforeEach((to, from, next) =>{
  const { cart } = useStore()
  // to去哪个页面？
  console.log(to.path)
  // 没有登录的用户就不能访问/member/checkout
  if(cart.isLogin === false && to.path === '/member/checkout'){
    Message.warning('没有登录，不能访问')
    const url = '/login?redirect=' + to.fullPath
    next(url)
  }else {
    next()
  }
})
export default router
